﻿
using CommonServiceLocator;
using MS.Common.Context;
using MS.Common.Helpers;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Threading;
using wpf.Triage;
using wpf.Triage.DataModel;
using Wpf.Models;

namespace wpf.Triage
{
    /// <summary>
    /// 过敏史
    /// </summary>
    public class ExtService
    {
        #region 属性
        /// <summary>
        /// 延迟加载对象  2022-03-28
        /// </summary>
        private static readonly Lazy<ExtService> _lazy =
            new Lazy<ExtService>(() => new ExtService(), LazyThreadSafetyMode.PublicationOnly);

        /// <summary>
        /// 单例对象  2022-03-28
        /// </summary>
        public static ExtService Instance => _lazy.Value;
        /// <summary>
        /// 接口工具服务接口   2022-03-28
        /// </summary>
        private readonly InterfaceToolHelper jsService;

        /// <summary>
        /// 接口工具    2022-01-27
        /// </summary>
        private readonly IRestClient client;

        private readonly IRestClient clientExt;
        #endregion

        #region 构造方法
        /// <summary>
        /// 构造方法   2022-03-28
        /// </summary>
        private ExtService()
        {
            jsService = InterfaceToolHelper.Instance;
            client = ServiceLocator.Current.GetInstance<IRestClient>();
            clientExt = new RestClient(ConfigHelper.GetConfig("ExtServicesUrl"));
        }
        #endregion

        #region PatAllergyServices
        /// <summary>
        /// 获取患者过敏史
        /// </summary>
        /// <param name="patientid">患者ID</param>
        /// <returns></returns>
        public List<PatAllergyinfo> GetPatAllergyInfoNew(string patientid)
        {
            var result = new List<PatAllergyinfo>();
            try
            {
                var request = new RestRequest("api/PatAllergyinfo/GetPatAllergyInfoNew", Method.GET);
                request.AddParameter("patientid", patientid); // replaces matching token in request.Resource

                var response = client.Execute(request);
                var responseApi = JsonConvert.DeserializeObject<ResponseApi<List<PatAllergyinfo>>>(response.Content);
                result = responseApi.data;
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }

            var hisAllergy = GetHisAllergyInfo(PatientContext.CurrPatient.PatientInfo);
            if (hisAllergy != null)
            {
                result.AddRange(hisAllergy);
            }
            return result;
        }
        /// <summary>
        /// 获取HIS过敏史信息
        /// </summary>
        /// <param name="pat"></param>
        /// <returns></returns>
        private List<PatAllergyinfo> GetHisAllergyInfo(PatientInfo pat)
        {
            try
            {
                 
                var jsScript = jsService.GetInterfaceToolByCode("GetHisAllergyInfo");
                if (jsScript != null)
                {
                    var script = new ScriptContent()
                    {
                        FunctionName = jsScript.FUNCTIONNAME,
                        JavaScriptCode = jsScript.JAVASCRIPTCODE,
                        Data = JsonConvert.SerializeObject(pat)
                    };
                    var commonResult = JsonConvert.DeserializeObject<CommonResult>(jsService.Convert(script));
                    if (commonResult.Result && commonResult.ReturnData != null)
                    {
                        var result = JsonConvert.DeserializeObject<List<PatAllergyinfo>>(commonResult.ReturnData.ToString());
                        return result;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
                return null;
            }
        }
        #endregion

        #region PatientServices
        public PatientInfo GetPatientInfoByPvid(string pvid)
        {
            var result = new PatientInfo();
            try
            {
                var request = new RestRequest("api/PatientInfo/GetPatientInfoByPvid", Method.GET);
                request.AddParameter("pvid", pvid);
                IRestResponse response = client.Execute(request);
                var responseApi = JsonConvert.DeserializeObject<ResponseApi<PatientInfo>>(response.Content);
                result = responseApi.data;
               
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }
            return result;

        }

        /// <summary>
        /// 获取就诊历史记录List
        /// </summary>
        /// <param name="pvid"></param>
        /// <returns></returns>
        //public List<PatHisvisitRecord> GetHisVisitRecordListByPvid(string pvid)
        //{
        //    var result = new List<PatHisvisitRecord>();
        //    try
        //    {
        //        var request = new RestRequest("api/PatientInfo/GetHisVisitRecordListByPvid", Method.GET);
        //        request.AddParameter("pvid", pvid);
        //        IRestResponse response = client.Execute(request);
        //        var responseApi = JsonConvert.DeserializeObject<ResponseApi<List<PatHisvisitRecord>>>(response.Content);
        //        result = responseApi.data;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.GetLogHelper().Error(ex);
        //    }
        //    return result;
        //}


        /// <summary>
        /// 添加流转日志
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        //public ResponseApi<CommonResult> AddTransferRecord(PatTransferrecord info)
        //{
        //    var result = new ResponseApi<CommonResult>();
        //    try
        //    {
        //        var request = new RestRequest("api/PatientInfo/AddTransferRecord", Method.POST);
        //        var json = JsonConvert.SerializeObject(info);
        //        request.AddJsonBody(json);
        //        IRestResponse response = client.Execute(request);
        //        result = JsonConvert.DeserializeObject<ResponseApi<CommonResult>>(response.Content);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.code = -1;
        //        result.msg = ex.Message;
        //        LogHelper.GetLogHelper().Error(ex);
        //    }
        //    return result;
        //}

        /// <summary>
        /// 指定叫号人员
        /// </summary>
        /// <param name="pat"></param>
        /// <returns></returns>
        //public CommonResult CallOppointPatient(JHECIS_CALL_PATIENT_INFO pat)
        //{
        //    var result = new CommonResult();
        //    try
        //    {
        //        var request = new RestRequest("api/JiaoHao/CallOppointPatient", Method.POST);
        //        var json = JsonConvert.SerializeObject(pat);
        //        request.AddJsonBody(json);
        //        IRestResponse response = clientExt.Execute(request);
        //        result = JsonConvert.DeserializeObject<CommonResult>(response.Content);
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Result = false;
        //        result.ErrMsg = ex.Message;
        //        LogHelper.GetLogHelper().Error(ex);
        //    }
        //    return result;
        //}
        #endregion

        #region FiveCentersService
        /// <summary>
        /// 保存五大中心数据（添加、修改）
        /// </summary>
        /// <param name="PatientVisitInfo"></param>
        /// <returns></returns>
        public ResponseApi<CommonResult> SaveFiveCenterData(PatientInfo patinfo)
        {
            var result = new ResponseApi<CommonResult>();
            try
            {
                #region PatientVisitInfo 基本信息
                var request = new RestRequest("api/FiveCenter/SaveFiveCenterData", Method.POST);
                var json1 = JsonConvert.SerializeObject(patinfo);
                request.AddJsonBody(json1);
                IRestResponse response = client.Execute(request);
                result = JsonConvert.DeserializeObject<ResponseApi<CommonResult>>(response.Content);
                #endregion
            }
            catch (Exception ex)
            {
                result.code = -1;
                result.msg = ex.Message;
                LogHelper.GetLogHelper().Error(ex);
            }
            return result;
        }
        #endregion

        #region RFIDManageService

        /// <summary>
        /// 获取腕带/RFID设备
        /// </summary>
        /// <param name="listWhere"></param>
        /// <returns></returns>
        //public List<RFIDModel> GetRFID(List<object> listWhere)
        //{
        //    var result = new List<RFIDModel>();
        //    try
        //    {
        //        var request = new RestRequest("api/RFID/GetRFID", Method.GET);
        //        request.AddParameter("listWhere", listWhere);

        //        IRestResponse response = client.Execute(request);
        //        var responseApi = JsonConvert.DeserializeObject<ResponseApi<List<RFIDModel>>>(response.Content);
        //        if (responseApi != null)
        //            result = responseApi.data;
        //    }
        //    catch (Exception ex)
        //    {
        //        LogHelper.GetLogHelper().Error(ex);
        //    }
        //    return result;
        //}

        #endregion

         

        #region Js

        private int setTimeOut = 2000;
        public string Convert(ScriptContent script)
        {
            var result = string.Empty;
            try
            {
                using (CodeTimer timer = new CodeTimer(script.FunctionName))
                {
                    var resource = "api/JavaScript/Convert";
                    if (script.ScriptType == 1)
                    {
                        resource = "api/PythonScript/Convert";
                    }
                    var request = new RestRequest(resource, Method.POST);
                    request.Timeout = setTimeOut;
                    var json = JsonConvert.SerializeObject(script);
                    LogHelper.GetLogHelper().Trace("接口参数：" + script.Data);
                    request.AddJsonBody(json); // replaces matching token in request.Resource

                    var response = client.Execute(request);
                    var responseApi = JsonConvert.DeserializeObject<ResponseApi<string>>(response.Content);
                    result = responseApi.data;
                }
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }

            return result;
        }

        public InterfaceToolEntity GetInterfaceToolByCode(string interfaceCode)
        {
            var result = new InterfaceToolEntity();
            try
            {
                var request = new RestRequest("api/InterfaceTool/GetInterfaceToolByCode", Method.GET);
                request.Timeout = setTimeOut;
                request.AddParameter("interfaceCode", interfaceCode);

                var response = client.Execute(request);
                var responseApi = JsonConvert.DeserializeObject<ResponseApi<InterfaceToolEntity>>(response.Content);
                result = responseApi.data;
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }

            return result;
        }

        #endregion

        /// <summary>
        /// 根据sql获取DataSet  2023-06-20
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public CommonResult ExcuteSql(string sql)
        {
            var result = new CommonResult();
            try
            {
                var request = new RestRequest("api/DataSet/GetDataSet", Method.GET);
                request.AddParameter("sql", sql);
                IRestResponse response = client.Execute(request);
                result = JsonConvert.DeserializeObject<CommonResult>(response.Content);
            }
            catch (Exception ex)
            {
                LogHelper.GetLogHelper().Error(ex);
            }
            return result;
        }

        /// </summary>  2023-06-20
        /// <param name="str">要过滤SQL字符的字符串。</param>
        /// <returns>已过滤掉SQL字符的字符串。</returns>
        public static string ReplaceSQLChar(string str)
        {
            if (str == String.Empty)
                return String.Empty;
            str = str.Replace("'", "‘");
            str = str.Replace(";", "；");
            str = str.Replace(",", ",");
            str = str.Replace("?", "?");
            str = str.Replace("<", "＜");
            str = str.Replace(">", "＞");
            str = str.Replace("@", "＠");
            str = str.Replace("=", "＝");
            str = str.Replace("*", "＊");
            str = str.Replace("&", "＆");
            str = str.Replace("#", "＃");
            str = str.Replace("%", "％");
            return str;
        }
        /// <summary>
        /// 根据Key与主键更新列值  2023-06-20
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public CommonResult UpdateKnowlege(string key, string val, string id)
        {
            val = ReplaceSQLChar(val);
            string sql = $"update jhecis_triage_regulation set {key}='{val}' where id='{id}'";
            return ExcuteSql(sql);
        }

        /// <summary>
        /// 插入一条空规则  2023-06-20
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public CommonResult AddKnowlege()
        {
            string id = DateTime.Now.ToString("yyyyMMddHHmmss");
            string sql = $"insert into jhecis_triage_regulation (ID, CONTROL_NAME, MODULE_NAME, VALIDATE_RULE, MESSAGE_INFO, ISMANDATORY, VERTYPE, VERRANGE, RELATION_CONTROL_NAME, RELATION_CONTROL_VAL, PRIORITY, HOSPITALCOMPOUNDCODE, PID)values('{id}', '', '分诊', '', '', 1, '赋值', '文本变化', 'TriageLevel', '', null, '1,2', null)";
            var res = ExcuteSql(sql);
            res.ReturnData = id;
            return res;
        }
        /// <summary>
        /// 删除一条规则  2023-06-20
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public CommonResult DelKnowlege(string ID)
        {
            string sql = $"delete jhecis_triage_regulation  where ID='{ID}'";
            return ExcuteSql(sql);
        }

    }

}
